#include <iostream>
#include <vector>

using namespace std;

// https://leetcode.cn/problems/find-closest-node-to-given-two-nodes/?envType=daily-question&envId=2025-05-30
// 2359. 找到离给定两个节点最近的节点

class Solution
{
public:
    int closestMeetingNode(vector<int> &edges, int node1, int node2)
    {
        int n = edges.size();
        auto dealDistance = [&](int curNode)
        {
            vector<int> dic(n, n);
            int distance = 0;
            for (int i = curNode; dic[i] == n && i != -1; i = edges[i])
            {
                dic[i] = distance++;
            }
            return dic;
        };
        vector<int> dist1 = dealDistance(node1);
        vector<int> dist2 = dealDistance(node2);

        int ans = -1;
        int minMaxDist = 2 * n;
        for (int i = 0; i < n; ++i)
        {
            if (dist1[i] != n && dist2[i] != n)
            {
                int maxDist = max(dist1[i], dist2[i]);
                if (maxDist < minMaxDist)
                {
                    minMaxDist = maxDist;
                    ans = i;
                }
            }
        }

        return ans;
    }
};

int main()
{
    Solution solution{};
    vector<int> edges{2, 2, 3, -1};
    cout << solution.closestMeetingNode(edges, 0, 1) << endl;
    return 0;
}